package 基础篇.线程通信.同步监视器通信;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author IBM CHEN ZHI KAN
 * @create 2018/7/28
 */
public class Account {
  private String accountNo;//账户编号
  private double balance;//账户余额
  private static boolean flag=false;
  public Account(String accountNo, double balance) {
    this.accountNo = accountNo;
    this.balance = balance;
  }

  public String getAccountNo() {
    return accountNo;
  }

  public void setAccountNo(String accountNo) {
    this.accountNo = accountNo;
  }

  public double getBalance() {
    return balance;
  }

  public void setBalance(double balance) {
    this.balance = balance;
  }
  //取钱
  public synchronized void draw(double drawAmount){
   try{
      //如果当前旗标为true，则说明账户有钱，不需要阻塞，开始取钱
      if(balance-drawAmount<0){
        this.wait();
      }else {
     //执行取钱操作
     balance-=drawAmount;
     System.out.println(Thread.currentThread().getName()+"开始取钱，余额为："+balance);
     //标记账户存款为false
     flag=false;
     notifyAll();
      }
   }catch (Exception e){
    e.printStackTrace();
   }
  }
  //存钱
  public synchronized void deposit(double depositAmount){
    try{
      //如果当前旗标为false，则说明账户没钱，不需要阻塞，开始存钱
      if(balance<0){
        this.wait();
      }else{
        balance+=depositAmount;
        System.out.println(Thread.currentThread().getName()+"开始存钱，余额为："+balance);
        //将表示账户是否已有存款的旗标为true
        flag=true;
        notifyAll();
      }
    }catch (Exception e){
      e.printStackTrace();
    }
  }
}
